//
//  TabbarViewController.swift
//  MyTest
//
//  Created by guanzhongwang on 2021/4/1.
//

import UIKit

class TabbarViewController: UITabBarController {
    private var changeTitle:(()->Void)?
    private var items:Array<TabbarCustomItem>=[]
    private var loading = false
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        let main = UINavigationController.init(rootViewController: MainViewController())
        let vedio = UINavigationController.init(rootViewController: VedioMianViewController())
        let profile = UINavigationController.init(rootViewController: ProfileViewController())
        
        let images:Array<String>=["mainnormal","vedio","profile"]
        let titles:Array<String>=["首页","视频","未登录"]
        let navs = [main,vedio,profile]
        for i in 0..<navs.count {
            let nav = navs[i]
            nav.tabBarItem.image = UIImage(named: images[i])
            nav.title = titles[i]
            items.append(TabbarCustomItem.init(title: titles[i], imageName: images[i] , nav: nav,canRefersh: i == navs.count-1 ? false:true))
        }
        changeTitle = {
            if(DataManager.login){
                profile.tabBarItem.title = "我的"
            }else{
                profile.tabBarItem.title = "未登录"
            }
        }
        changeTitle?()
        self.setViewControllers(navs,animated: false)
        
        tabBar.backgroundColor = .white
        
        tabBar.tintColor  = UIColor(hexString: "#ED4742")
        tabBar.unselectedItemTintColor = .black
        tabBar.isTranslucent = false
        
        NotificationMananger.addNotification(.LoginCompletion, target: self, selector: #selector(loginResult))
        
        NotificationMananger.addNotification(.Custom(name: "StopLoading\(main.description)"), target: self, selector: #selector(refershComplet))
    }
    
    @objc func refershComplet(notification:Notification){
        let index = tabBar.items?.firstIndex(where: { (t) -> Bool in
            return (notification.object as! String) == t.title
        })
        let nav = items[index!]
        nav.wellDone?()
    }
    @objc func loginResult(){
        self.changeTitle?()
    }
    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
        // 找出当前点击的item位置
        let index = tabBar.items?.firstIndex(where: { (t) -> Bool in
            return item.title == t.title
        })
        let controller = items[index!]
        // 找出所有buttons
        var buttons:Array<UIView> = []
        for sb in tabBar.subviews {
            if sb.isKind(of: NSClassFromString("UITabBarButton")!) {
                buttons.append(sb)
            }
        }
        // 找出被点击的button
        let btn = buttons[index!]
        for sb in btn.subviews {
            // 找出ImageView
            if sb.isKind(of: NSClassFromString("UITabBarSwappableImageView")!) {
                if selectedIndex == index && index == 0{
                    SystemLog(selectedIndex)
                    guard controller.canRefersh && !controller.loading else {
                        // 设置动画
                        let animation = CABasicAnimation.init(keyPath: "transform.scale")
                        animation.duration = 0.3
                        animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
                        animation.fromValue = 0.6
                        animation.toValue = 1.0
                        sb.layer.add(animation, forKey: "scale\(item.title!)")
                        return
                    }
                    
                    let image = UIImageView(image: UIImage(named: "tabloading")?.withRenderingMode(.alwaysTemplate))
                    image.backgroundColor = .white
                    image.tintColor = RED_COLOR
                    sb.addSubview(image)
                    // 1.创建动画
                    let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z")
                    // 2.设置动画的属性
                    rotationAnim.fromValue = 0
                    rotationAnim.toValue = Double.pi * 2
                    rotationAnim.repeatCount = MAXFLOAT
                    rotationAnim.duration = 1
                    // 这个属性很重要 如果不设置当页面运行到后台再次进入该页面的时候 动画会停止
                    rotationAnim.isRemovedOnCompletion = false
                    // 3.将动画添加到layer中
                    sb.layer.add(rotationAnim, forKey: "rotation\(item.title!)")
                    // 通知controller刷新
                    NotificationMananger.post(.Custom(name: "Loading\(controller.controller.description)"))
                    controller.loading = true
                    controller.wellDone = {
                        controller.loading = false
                        sb.layer.removeAllAnimations()
                        image.removeFromSuperview()
                        controller.controller.tabBarItem.image = UIImage(named:controller.imageName)
                    }
                }else{
                    items[selectedIndex].wellDone?()
                    // 设置动画
                    let animation = CABasicAnimation.init(keyPath: "transform.scale")
                    animation.duration = 0.3
                    animation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
                    animation.fromValue = 0.6
                    animation.toValue = 1.0
                    sb.layer.add(animation, forKey: item.title)
                    if selectedIndex == index {
                        // 通知controller刷新
                        NotificationMananger.post(.Custom(name: "Loading\(controller.controller.description)"))
                    }
                }
            }
        }
    }
    override var childForStatusBarStyle: UIViewController?{
        return self.selectedViewController
    }
}
class TabbarCustomItem {
    var title:String=""
    var imageName:String=""
    var loading:Bool = false
    var canRefersh:Bool = true
    var wellDone:(()->Void)?={}
    var controller:UINavigationController
    init(title:String,imageName:String,nav:UINavigationController,canRefersh:Bool=true) {
        self.title = title
        self.imageName = imageName
        self.controller = nav
        self.canRefersh = canRefersh
    }
}
